package demo06238;

public class TicketSystemTest {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("=== 不安全售票测试 ===");
        testTicketSystem(new UnsafeTicketSystem(100), false);

        System.out.println("\n=== 同步方法售票测试 ===");
        testTicketSystem(new SafeTicketSystem(100), true);

        System.out.println("\n=== 同步块售票测试 ===");
        SafeTicketSystem syncBlockSystem = new SafeTicketSystem(100);
        Runnable syncBlockTask = () -> {
            for (int i = 0; i < 20; i++) {
                syncBlockSystem.sellTicketSyncBlock();
            }
        };
        startThreads(syncBlockTask);

        System.out.println("\n=== Lock售票测试 ===");
        SafeTicketSystem lockSystem = new SafeTicketSystem(100);
        Runnable lockTask = () -> {
            for (int i = 0; i < 20; i++) {
                lockSystem.sellTicketWithLock();
            }
        };
        startThreads(lockTask);
    }

    private static void testTicketSystem(Object ticketSystem, boolean isSafe) throws InterruptedException {
        Runnable task = () -> {
            for (int i = 0; i < 20; i++) {
                if (ticketSystem instanceof UnsafeTicketSystem) {
                    ((UnsafeTicketSystem)ticketSystem).sellTicket();
                } else if (isSafe) {
                    ((SafeTicketSystem)ticketSystem).sellTicketSyncMethod();
                }
            }
        };

        startThreads(task);

        Thread.sleep(2000);

        if (ticketSystem instanceof UnsafeTicketSystem) {
            System.out.println("最终剩余票数(不安全): " + ((UnsafeTicketSystem)ticketSystem).getTicketCount());
        } else {
            System.out.println("最终剩余票数(安全): " + ((SafeTicketSystem)ticketSystem).getTicketCount());
        }
    }

    private static void startThreads(Runnable task) {
        // 创建5个售票线程
        for (int i = 1; i <= 5; i++) {
            new Thread(task, "窗口" + i).start();
        }
    }
}

